package com.zhongge.util;

import java.sql.*;
import java.util.ResourceBundle;

/**
 * @ClassName JDBCUtil
 * @Description TODO 数据库工具类
 * @Author zhongge
 * @Version 1.0
 */
public class JDBCUtil {
    /**
     * 构造私有化
     */
    private JDBCUtil() {
    }
    //读取属性配置文件
    //资源包==》来获取配置文件中内容
    private static final ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
    //类加载时注册驱动 确保只需要注册一次驱动
    static {
        driver = bundle.getString("driver");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");

        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    //释放资源
    public static void close(Connection conn, PreparedStatement stmt, ResultSet re) {
        if (re != null) {
            try {
                re.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
